import sys
import os

# import helper
import re
from config import config
from PyInquirer import prompt
from simple_chalk import chalk
from argparse import ArgumentParser
from prompt_toolkit import prompt as gnuInput

rootDir = os.path.abspath(os.path.join(__file__, r"..\.."))

sys.path.append(rootDir)
# print(sys.path, "<---sys.path")

import common.index as common

# print("====>", common)

import wordTest.helper.sound as sound
import wordTest.helper.db as db

# print(sound, "<---------------sound")


# sys.argv => app.py arg1 arg2...
def showHelp():
    if len(sys.argv) < 2:
        print("tips : hello ^_^ ")
        sys.exit()


spaceCount = 0


def getPart(ls):
    global spaceCount
    part = []
    for v in ls:
        if not v == "\n":
            part.append(v)
        else:
            if len(part) > 0:
                return part
            else:
                spaceCount += 1
    return part


def getParts(lines):
    partList = []

    notSpaceCount = 0
    start = 0

    while start < len(lines):
        # 从剩余的行 获取一部分后，移动start索引
        restList = lines[start:]
        part = getPart(restList)
        partList.append(part)

        notSpaceCount = sum([len(p) for p in partList])
        start = notSpaceCount + spaceCount

    partList = [cleanEnter(p) for p in partList if p]

    return partList


def cleanEnter(part):
    return [line.replace("\n", "") for line in part]


def getPhraseListFrom(parts):
    phraseList = []
    for part in parts:
        # print(part)

        # [
        # 'how can I do sth?'
        # '我如何才能做到某事？'
        # ---
        # how can I get there?
        # 我如何才能到那里？
        # how can I make you happy?
        # 我如何才能使你高兴？
        # ]

        # part -> dict

        # part = dict(part) ??

        phraseObj = {}
        # 'phrase' part[0]
        phraseObj["phrase"] = part[0]
        # 'meaning'  part[1]
        phraseObj["meaning"] = part[1]
        examples = []
        phraseObj["examples"] = examples
        exampleLines = part[3:]
        exampleParts = common.toGroups(exampleLines, 2)
        # print('\n=======',examLines)
        for examplePart in exampleParts:
            #  line
            en = examplePart[0]
            cn = examplePart[1]
            examDict = {}
            examDict["en"] = en
            examDict["cn"] = cn
            examples.append(examDict)

        # print("\n ---->examples", examples)

        phraseList.append(phraseObj)

    return phraseList


def main():
    lines = common.getDailyFileContent(
        args.get("book"), args.get("dailyFileSn"), config
    )
    parts = getParts(lines)
    phraseList = getPhraseListFrom(parts)

    startTest(phraseList)


def delLastBiaoDian(answer):
    # replace ? ! .
    pattern = re.compile("(\?|\.|\!)$")
    return pattern.sub("", answer)
    # answer = answer.lower().rstrip('?').rstrip('.').rstrip('!')
    # return answer


def checkAnswer(rightAnswer, userAnswer):
    pattern = re.compile(r"\s+")
    return pattern.sub(" ", delLastBiaoDian(rightAnswer).lower()) == pattern.sub(
        " ", delLastBiaoDian(userAnswer).lower()
    )


# 前缀
liZiQianZui = "."
startTime = common.getNow()


def startTest(phraseList):
    rightCount = 0

    # print()
    print(
        # chalk.cyan("短语" + ("测试" if args.get("isTest") else "练习") + "开始...\n")
        ""
        + chalk.bgGray("(按a查看答案, 按s跳过, 按x退出, 末尾标点可省略, 空格个数不限)")
    )

    hasSeeOrSkip = False

    while True:
        phrase = phraseList[rightCount]
        meaning = phrase["meaning"]
        answer = phrase["phrase"]
        examples = phrase["examples"]

        print()
        tips = (
            common.headStr(common.percentStr(rightCount + 1, len(phraseList)))
            + meaning
            + "\n"
            + common.headStr()
        )
        userAnswer = gnuInput(tips)

        if userAnswer.lower() == "x":
            sys.exit()

        if userAnswer.lower() == "a":
            hasSeeOrSkip = True
            common.headLogWarn(answer)

        elif userAnswer.lower() == "s":
            hasSeeOrSkip = True
            common.headLogWarn(answer)
            rightCount += 1

        elif checkAnswer(answer, userAnswer):
            # common.headLog("Right!")
            sound.playGood()
            rightCount += 1

            exampleRightCount = 0
            w = 10
            while exampleRightCount < len(examples):
                example = examples[exampleRightCount]
                tips2 = (
                    common.headStr(
                        common.percentStr(exampleRightCount + 1, len(examples)) + ")", w
                    )
                    + example["cn"]
                    + "\n"
                    + common.headStr("", w)
                )

                userAnswer = gnuInput(tips2)

                if userAnswer.lower() == "x":
                    sys.exit()

                rightAnswer = example["en"]
                if checkAnswer(rightAnswer, userAnswer):
                    # headLog("Right~", w=w)
                    sound.playGood()
                    exampleRightCount += 1
                elif userAnswer.lower() == "s":
                    hasSeeOrSkip = True
                    common.headLogWarn(rightAnswer, w=w)
                    exampleRightCount += 1
                elif userAnswer.lower() == "a":
                    hasSeeOrSkip = True
                    common.headLogWarn(rightAnswer, w=w)
                else:
                    common.headLogWarn("Try one more time :)", w=w)
                    sound.playBad()

        else:
            common.headLogWarn("Try it again :)")
            sound.playBad()

        if rightCount == len(phraseList):
            if hasSeeOrSkip:
                sound.playTips()
                print()
                print(chalk.yellow("借助提示道具通过，仍需努力鸭~~"))

            if (args.get("isTest") and not hasSeeOrSkip) or not args.get("isTest"):
                common.savePassResultToFile(
                    args.get("user"),
                    args.get("book"),
                    args.get("dailyFile"),
                    args.get("isTest"),
                    config,
                )

                if args.get("isTest") and not hasSeeOrSkip:
                    common.headLog(chalk.magenta("\n\nBingo!\n"), w=0)
                    sound.playWin()
                    db.writeTestData(
                        args.get("user"),
                        startTime,
                        args.get("dailyFile"),
                        "phrase",
                        args.get("book"),
                    )
                else:
                    common.headLog(chalk.magenta("\n\nFinish!\n"), w=0)

            break


lastResult = common.getLastResult(config)


def startAdmin():
    os.system("")

    print(cargs, "<----")

    print()
    if not cargs.action == "create":
        print(chalk.yellow("action 只能为 create 哦~~  \nptest -h 查看帮助"))
        sys.exit(1)

    books = common.getBooks(config)
    if not cargs.book in books:
        print(chalk.yellow("短语合集 %s 不存在，可选合集如下:" % cargs.book))
        print(books)
        sys.exit(1)

    common.createBookDailyFiles(cargs.book, config)


args = {}
cargs = {}
if __name__ == "__main__":
    # showHelp()

    if len(sys.argv) == 1:
        # ptest
        args = common.getArgsByQuestions(lastResult, config, "短语")

        main()
    else:
        cargs = common.getCliArgs("短语")
        startAdmin()
